package com.starry.core.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取浏览器信息
 *
 * @author xiaoke
 */
public class UserAgentParser {
    public static UserAgentInfo parseUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");

        if (userAgent == null) {
            return new UserAgentInfo("Unknown", "Unknown");
        }

        // 操作系统的正则表达式
        Pattern osPattern = Pattern.compile(
                "(?i)(windows|macintosh|linux|android|ios|symbian|blackberry|webos)"
        );
        Matcher osMatcher = osPattern.matcher(userAgent.toLowerCase());

        // 浏览器类型的正则表达式
        Pattern browserPattern = Pattern.compile(
                "(?i)(chrome|firefox|safari|msie|trident|edge)"
        );
        Matcher browserMatcher = browserPattern.matcher(userAgent.toLowerCase());

        String os = "Unknown";
        if (osMatcher.find()) {
            os = osMatcher.group();
        }

        String browser = "Unknown";
        if (browserMatcher.find()) {
            browser = browserMatcher.group();
        }

        return new UserAgentInfo(os, browser);
    }

    @Data
    public static class UserAgentInfo {
        private final String os;
        private final String browser;
    }
}
